读书笔记 numpy入门 第2章 数据索引

https://github.com/jakevdp/PythonDataScienceHandbook

一维数组里进行索引

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import numpy as np
np.random.seed(0)

x1 = np.random.randint(10, size=6) # 一维数组
x2 = np.random.randint(10, size=(3, 4)) # 二维数组
x3 = np.random.randint(10, size=(3, 4, 5)) # 三维数组

x1

>>> array([5, 0, 3, 3, 7, 9])

x1[0]

>>> 5

x1[4]

>>> 7

x1[-1]
>>> 9

x1[-2]
>>> 7

多维数组里进行索引

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
x2

>>> array([[3, 5, 2, 4], [7, 6, 8, 8], [1, 6, 7, 7]])

x2[0, 0]

>>> 3

x2[2, 0]

>>> 1

x2[2, -1]

>>> 7

x2[0, 0] = 12
x2

>>> array([[12, 5, 2, 4], [ 7, 6, 8, 8], [ 1, 6, 7, 7]])

修改浮点数

如果把x1的位置0元素改为浮点数,那结果会被截短成整型。

1
2
3
4
x1[0] = 3.14159
x1

>>> array([3, 0, 3, 3, 7, 9])